package com.doge.walknovel.analysis

import com.appsflyer.AppsFlyerConversionListener
import com.appsflyer.AppsFlyerLib
import com.doge.walknovel.utils.OAIDUtils
import com.doge.walknovel.utils.appContext
import com.doge.walknovel.utils.getString
import com.doge.walknovel.utils.log
import com.doge.wnpro.BuildConfig
import com.doge.wnpro.R
import com.github.gzuliyujiang.oaid.DeviceID

object AppsFlyerHelper {
    private val devKey by lazy { getString(R.string.apps_flyer_id) }
    private var conversationData: MutableMap<String, Any>? = null
    val afStatus: String?
        get() = conversationData?.get("af_status")?.toString() //  af_status = Organic
    val origCost: String?
        get() = conversationData?.get("orig_cost")?.toString() //  orig_cost = Float.

    fun initialized() {
        val conversionDataListener = object : AppsFlyerConversionListener {
            override fun onConversionDataSuccess(data: MutableMap<String, Any>?) {
                conversationData = data
            }

            override fun onConversionDataFail(error: String?) {
                log("AppsFlyer error onConversionDataFail :  $error")
            }

            override fun onAppOpenAttribution(data: MutableMap<String, String>?) {
            }

            override fun onAttributionFailure(error: String?) {
                log("AppsFlyer error onAttributionFailure :  $error")
            }
        }

        val appsFlyer = AppsFlyerLib.getInstance()
        appsFlyer.init(devKey, conversionDataListener, appContext)
        val androidId = DeviceID.getAndroidID(appContext)
        val oaId = OAIDUtils.id
        val imei = DeviceID.getUniqueID(appContext)
        if (androidId?.isNotEmpty() == true) {
            appsFlyer.setAndroidIdData(androidId)
        }
        if (oaId?.isNotEmpty() == true) {
            appsFlyer.setOaidData(oaId)
        }
        if (imei?.isNotEmpty() == true) {
            appsFlyer.setImeiData(imei)
        }
        log("AppsFlyerHelper start initialized key $devKey androidId $androidId oaId $oaId imei $imei")
        appsFlyer.setDebugLog(BuildConfig.DEBUG)
        appsFlyer.start(appContext)

    }
}